<template>
    <div class="app-container" v-loading="loading">
        <levelbar></levelbar>
        <el-form label-width="100px" class="app-content" :rules="rules" :model="ruleForm" ref="ruleForm" label-position="right">
            <div class="box">
                <div class="appTitle">新增评分</div>
                <div class="appTop">评分项</div>
                <div class="appCon">
                    <el-row>
                        <el-col :span='6'>
                            <el-form-item label="评分日期：" prop="date">
                                <el-date-picker
                                    v-model="ruleForm.date"
                                    :clearable="false"
                                    :editable="false" 
                                    :disabled="true"
                                    type="date"
                                    placeholder="请选择评分日期"
                                    style="width:100%">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div v-for='(site,index) in ruleForm.ratingName' :key="index">
                        <el-row>
                            <el-col :span='6' class='rating'>
                                <el-form-item :label="'评分项'+(index+1)+'：'" :prop="'ratingName.' + index + '.sRatingName'" :rules="[{required: true, message: '评分项名称不能为空', trigger: 'blur'},{ pattern: /^[^ ]+$/, message: '请勿输入空格', trigger: 'change'}]">
                                    <el-input v-model="site.sRatingName" placeholder="请输入评分项名称" :maxlength="5"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span='6' class='rating'>
                                <el-form-item label="总分：" :prop="'ratingName.' + index + '.sScore'" :rules="[{required: true, message: '总分不能为空', trigger: 'blur'},{ pattern: /^([1-9]\d?|100)$/, message: '请输入1到100之间的正整数', trigger: 'blur' }]">
                                    <el-input v-model="site.sScore" placeholder="请输入总分" :maxlength="3"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6" v-if='index != 0'>
                                <el-button class="delBtn" type="text" @click.prevent="removeDomain(index)"><i class="el-icon-delete"></i></el-button>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <el-button type="text" @click="addRating" class="addBtn" v-if='ruleForm.ratingName.length != 6'><i class="el-icon-plus"></i> 继续添加</el-button>
                <div class="footer">
                    <el-button @click="goBack">返 回</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')" >下一步</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import { saveScore, getSchoolScore} from 'api/wisdom';
import { mapGetters } from 'vuex';
import moment from 'moment'

export default{
    name: 'addRate',
    components: {Levelbar},
    data() {
        return { 
            ruleForm: {
                date: new Date(),
                schoolName: '',
                ratingName: [] // 评分项数据
            },
            addStatus: false,
            loading: true,
            rules: {
                schoolName: [
                    { required: true, message: '请选择学校', trigger: 'change' }
                ],
                date: [
                    { type: 'date', required: true, message: '请选择评分日期', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this._getSchoolScore();
    },
    computed: {
        ...mapGetters([
            'schoolId',
            'schoolName'
        ])
    },
    methods: {
        // 获取上一次的记录 有就填充 没有就 默认添加一条 评比项
        _getSchoolScore() {
            let json={
                fSchoolId: this.schoolId
            }
            getSchoolScore(json).then(res => {
                this.loading=false;
                if (res.data.content.length) {
                    res.data.content.forEach((item) => {
                        this.ruleForm.ratingName.push({sRatingName: item.sRatingName, sScore: item.sScore})
                    })
                } else {
                    this.ruleForm.ratingName=[{sRatingName: '', sScore: ''}]
                }
            }).catch(() => {
                this.loading=false;
            })
        },
        // 提交
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let sRatingName = '';
                    let sPosition = '';
                    let sScore = '';
                    let arrList = [];
                    for (var i = 0;i<this.ruleForm.ratingName.length;i++) {
                        if (arrList.indexOf(this.ruleForm.ratingName[i].sRatingName)==-1) {
                            arrList.push(this.ruleForm.ratingName[i].sRatingName);
                            sRatingName += this.ruleForm.ratingName[i].sRatingName + ';';
                            sPosition += (i+1) + ';';
                            sScore += this.ruleForm.ratingName[i].sScore + ';';
                        } else {
                            this.$message({
                                type: 'error',
                                message: '评分项重复'
                            })
                            return '';
                        }
                    }
                    sScore = sScore.substring(0, sScore.length-1);
                    sRatingName = sRatingName.substring(0, sRatingName.length-1);
                    sPosition = sPosition.substring(0, sPosition.length-1);
                    let str = this.addStatus ? '是否确认保存？将清空修改项旧数据' : '确定要保存评分项并进入“下一步”吗？'
                    this.$confirm(str, ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        this.loading = true;
                        let json={
                            sRatingName,
                            sScore,
                            sPosition,
                            sRatingTime: moment(this.ruleForm.date).format('YYYY-MM-DD')+' 00:00:00', // 评分时间
                            sSchoolName: this.schoolName, // 考勤设备学校"
                            fSchoolId: this.schoolId
                        }
                        this._saveScore(json);
                    })
                }
            });
        },
        _saveScore(json) {
            saveScore(json).then(res => {
                this.loading = false;
                this.$message({
                    type: 'success',
                    message: '保存成功'
                })
                this.$store.dispatch('UpdateCache', true);// 修改 和查看
                let ratingTime = moment(this.ruleForm.date).format('YYYY-MM-DD')+' 00:00:00';// 评分时间
                this.$router.push({ path: `/classScore/rateSet/${ratingTime}`});
                // window.history.back();      
            }).catch(() => {
                this.loading = false;
            })
        },
        removeDomain(index) {
            this.$confirm('确定要删除评分项'+(index+1)+'?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.ruleForm.ratingName.splice(index, 1);
            })
        },
        // 添加评分项
        addRating() {
            if (this.ruleForm.ratingName.length > 5) {
                this.$message({
                    type: 'warning',
                    message: '最多可添加6个评分项'
                })
                return '';
            }
            let NumberObj = {
                sRatingName: '',
                sScore: ''
            };
            this.ruleForm.ratingName.push(NumberObj)
        },
        goBack() {
            window.history.back();
        }
        // // 获取评分项
        // getRating() {
        //     getSchoolRatingInfo(this.schoolId).then(response => {
        //         let ratingName = [{sRatingName: '', sScore: ''}];
        //         if (response.data.content.length > 0) {
        //             this.addStatus = true;
        //             this.ruleForm.ratingName = response.data.content;
        //         } else {
        //             this.addStatus = false;
        //             this.ruleForm.ratingName = ratingName;
        //         }
        //     })
        // }
    }
}
</script>

<style lang="scss" scoped>
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    .app-levelbar {
        height: 35px;
    }
    .el-form{
        box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        background:#fff;
        padding-bottom:100px;
        .appCon{
            margin-top:50px;
        }
        .appTop{
            position: relative;
            font-size: 14px;
            color: rgb(106, 85, 72);
            padding-left: 16px;
            margin: 30px 0;
            display: block;
            &::after {
                position: absolute;
                content:'';
                width: 4px;
                height: 14px;
                background: #ff5e2c;
                left: 0;
                top: 3px;
            }
        }
        .appTitle{
            padding-top:8px;
            text-align: center;
            font-size: 18px;
            color: #333;
            line-height: 72px;
            font-weight: bold;
            font-family: Microsoft YaHei;
            border-bottom: 1px solid #ddd;
        }
        .box{
            padding: 0px 50px;
            background:#fff;
        }
       .footer{
            //margin-left: 15%;
            // text-align:center;
            text-align: center;
            margin-top: 50px;
        }
        .addBtn{
            margin:0px 0 50px 8px;
            font-size: 14px;
            color: #ff5e2c;
        }
        .delBtn {
            font-size: 20px;
            color:#999;
            margin-left:30px;
        }
        .imageBox{
            height:330px;
            margin-left:30px;
        }
        // .rating{
        //     margin:0 0 15px 2px;
        // }
    }
    
}

</style>
